package com.alex.task.quartz.config;

import com.alex.task.quartz.job.SampleJob;
import com.alex.task.quartz.job.SampleJob2;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SampleSchedulerConfig {

    private static String JOB_GROUP_NAME = "PJB_JOBGROUP_NAME";
    private static String TRIGGER_GROUP_NAME = "PJB_TRIGGERGROUP_NAME";

    // 实例化 Job -> JobDetail (bean)
    @Bean
    public JobDetail sampleJobDetail() {
        return JobBuilder
                .newJob(SampleJob.class)
                /*.withIdentity("sampleJob")*/
                .withIdentity("sampleJob", JOB_GROUP_NAME)
                .usingJobData("name", "xxxxx")
                .usingJobData("name", "world")
                .storeDurably().build();
    }

    @Bean
    public JobDetail sampleJobDetail2() {
        return JobBuilder
                .newJob(SampleJob.class)
                .withIdentity("sampleJob2")
                .usingJobData("name", "sampleJobDetail2")
                .storeDurably().build();
    }

    @Bean
    public JobDetail sampleJobDetail3() {
        return JobBuilder
                .newJob(SampleJob2.class)
                .withIdentity("sampleJob3")
                .usingJobData("name", "sampleJobDetail3")
                .storeDurably().build();
    }

    /**
     * 定时任务1：
     * Trigger 触发器示例1
     * 检测到 Trigger bean 时， quartz 会自动使用线程池执行定时任务
     * @return
     */
    @Bean
    public Trigger sampleJobTrigger () {
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder
                .simpleSchedule()
                .withIntervalInSeconds(2)
                .repeatForever();
        return TriggerBuilder.newTrigger()
                .forJob(sampleJobDetail())
                .withIdentity("sampleTrigger")
                .withSchedule(scheduleBuilder).build();
    }

    /**
     * Trigger 触发器示例2
     * SimpleScheduleBuilder
     * @return
     */
    @Bean
    public Trigger sampleJobTrigger2 () {
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder
                .simpleSchedule()
                .withIntervalInSeconds(5)
                .repeatForever();
        return TriggerBuilder.newTrigger()
                .forJob(sampleJobDetail2())
                .withIdentity("sampleTrigger2")
                .withSchedule(scheduleBuilder).build();
    }

    /**
     * Trigger 触发器示例3
     * CronScheduleBuilder
     * @return
     */
    @Bean
    public Trigger sampleJobTrigger3 () {
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
        return TriggerBuilder.newTrigger()
                .forJob(sampleJobDetail3())
                .withIdentity("sampleTrigger3")
                .withSchedule(scheduleBuilder).build();
    }
}
